<template>
	<view class="main" style="background-color: #FAFAFA;">
		<view class="now" style="margin-top: 10px;">
			<view class="titlexxx" style="padding: 10px 16px;background-color: #FFFFFF;display: flex;align-items: center;justify-content: space-between;">
				<view class="tttleft" style="color: #212121;font-weight: 700;">
					运行状态
				</view>
				<view class="tttright" style="color: #999;">
					{{ pointStatus == '' ? '离线' : pointStatus == 'OFFLINE' ? '离线' : '在线' }}
				</view>
			</view>
		</view>
		<view class="now" style="margin-top: 10px;">
			<view class="title" style="padding: 10px 16px;height: 26px;background-color: #FFFFFF;">实时监测数据</view>
			<view><u-line></u-line></view>
			<view class="content" style="padding: 15px 16px 0px 16px;background-color: #FFFFFF;">
				<u-row customStyle="padding-bottom:15px" v-for="(item, index) in currentDataList" :key="index">
					<u-col span="3" customStyle="color:#999999" >
						<view >{{item.pointName}}</view>
					</u-col>
					<u-col span="3"  customStyle="text-align:center">
						<view >{{item.value!=undefined?item.value:''}}{{ getUnit(item) }}</view>
					</u-col>	
					<u-col span="6" customStyle="text-align:right">
						<view >{{item.lastUpdated!=undefined?item.lastUpdated.slice(5):''}} </view>
					</u-col>
				</u-row>	
			</view>
		</view>
		<view class="old" style="margin-top: 10px;">
			<view class="title" style="padding: 10px 16px;height: 26px;background-color: #FFFFFF;">历史监测数据</view>
			<view><u-line></u-line></view>
			<view class="content" style="background-color: #FFF;">
				<view class="intitle" style="padding: 10px 16px;height: 26px;background-color: #FFFFFF;">数据时间范围</view>
				<view class="tags" style="display: flex;justify-content: center;">
					<view v-for="(item, index) in dateDruingList" :key="index" :style="getStyle(index)">
						<u-tag :text="item.text" :plain="!item.checked" shape="circle" type="warning" :name="index" @click="handDateClick">
						</u-tag>
					</view>
				</view>
				
				<view class="intitle" style="padding: 10px 16px;height: 26px;background-color: #FFFFFF;">自定义时间</view>
				<view class="sj" style="display: flex;padding: 0px 16px;align-items: center;">
					<view @click="a()" >
						<u--input placeholder="开始时间" border="surround" v-model="selfTimeDuring.start" suffixIcon="calendar-fill" readonly></u--input> 
					</view> 
					<view style="">{{'至'}}</view>
					<view  @click="b()" >
						 <u--input placeholder="结束时间" border="surround" v-model="selfTimeDuring.end" readonly suffixIcon="calendar-fill"></u--input>
					</view> 
				</view>
				
				<view class="intitle" style="padding: 10px 16px 5px 16px;height: 26px;background-color: #FFFFFF;">选择监测项目</view>
				<u-checkbox-group placement="row" v-model="indexList" @change="handChangePoint" style="padding: 0px 16px;display: flex;flex-wrap: wrap;">
					<u-checkbox :customStyle="{marginRight: '10px',marginTop:'5px'}" v-for="(item, index) in currentDataList"
								activeColor="#f9ae3d" :key="index" :label="item.pointName" :name="item.pointCode" :disabled="!ischange"> 
					</u-checkbox>
				 </u-checkbox-group>
				
				<view class="chars" style="padding: 10px 16px 10px 0px;display: flex;flex-direction: column;justify-content:center;align-items: center;">
					<u--text  :text="queryParam.siteName" :block="true"  customStyle="width:70vw;textAlign:center;margin-left:16px" :lines="2" align="center" :bold="true"></u--text>
					<view class="char" style="height: 260px;width: 100%;">
						<qiun-data-charts type="area" :opts="opts" :chartData="chartData"/>
					</view>
				</view>
				
			</view>
		</view>
		
		<u-datetime-picker ref="startPicker" :show="startTimeshow"  v-model="queryParam.start"    @cancel="startTimeshow=false" @confirm="timeconfirm('start',$event)"
		 mode="datetime"></u-datetime-picker>	
		 <u-datetime-picker ref="endPicker" :show="endTimeShow"  v-model="queryParam.end"   @cancel="endTimeShow=false" @confirm="timeconfirm('end',$event)"
		 mode="datetime"></u-datetime-picker>
	</view>
</template> 

<script> 

import croods from '@/common/croods-1.3.3.js';
window.croods = croods;
window.hydra =  require('../../../common/wst_hydra-1.0.0.js');
import coordtransform from 'coordtransform';
import {
	getHisAggData,
		queryMonitordata
	} from '@/common/api.js';
	export default {
		data() {
			return {
				ischange:true,
				startTimeshow:false,
				endTimeShow:false,
				chartData: {},
				queryParam: {
					siteId: '',
					siteName: '',
					start: Number(new Date())- 2*60*60*1000,
					end: Number(new Date()),
					aggregation: 'first',
					index: '',
					interval: 'm',					
					value: '5',					
				},
				pointStatus:'',
				selfTimeDuring:{
					start: '',
					end: '',
				},
				currentDataList:[],
				indexList:[],
				 opts: {
					color: ["#00FCF0"],
					padding: [15,50,0,15],
					enableScroll: false,
					legend: {},
					dataLabel: false,
					dataPointShape: false,
					xAxis: {
					  disableGrid: true,
					  labelCount:2,
					},
					yAxis: {
					  gridType: "dash",
					  dashLength: 2,
					  tofix:2,
					  splitNumber:5
					  
					},
					extra: {
					  area: {
						type: "curve",
						opacity: 0.2,
						addLine: true,
						width: 2,
						gradient: true,
						activeType: "hollow"
					  }
					}
			  },
				dateDruingList: [
					{
						checked: true,
						text: '2小时',
						code: '2'
					},
					{
						checked: false,
						text: '6小时',
						code: '6'
						
					},
					{
						checked: false,
						text: '12小时',
						code: '12'
					},
					{
						checked: false,
						text: '24小时',
						code: '24'
					},
					{
						checked: false,
						text: '48小时',
						code: '48'
					}
				],
			}
		},
		methods: {
			getUnit(item){
				if(item.value || item.value==0 || item.value===0.0){
					return item.unit
				}else{
					return
				}
			},
			goBack() {
				if(this.showQuery){
					this.showQuery =false;
				}else{
					uni.navigateBack();
				}
			},
			a(){
				if(this.ischange){
					this.startTimeshow=true;
				}
			},
			b(){
				if(this.ischange){
					this.endTimeShow=true;
				}
			},
			hideKeyboard() {
				uni.hideKeyboard()
			},	
			timeconfirm(e,newValue){
				const timeFormat = uni.$u.timeFormat;
				if(e=='start'){
						this.queryParam.start = newValue.value;
						this.selfTimeDuring.start = timeFormat(this.queryParam.start, 'yyyy-mm-dd hh:MM');
						this.startTimeshow=false;
				}
				if(e=='end'){
						this.queryParam.end = newValue.value
						this.selfTimeDuring.end =  timeFormat(this.queryParam.end, 'yyyy-mm-dd hh:MM');
						this.endTimeShow=false;
				}
				
				if(this.selfTimeDuring.start && this.selfTimeDuring.end){
					const start = new Date(this.selfTimeDuring.start)
					const end = new Date(this.selfTimeDuring.end)
					let time = Math.abs(end-start)
					const bi = 1000 * 60 * 60 * 24 * 31
					if(time>bi){
						uni.$u.toast('最大自定义时间范围为31天，请重新选择')
						this.selfTimeDuring.start = ''
						this.selfTimeDuring.end = ''
						this.queryParam.start = Number(new Date())- 2*60*60*1000
						this.$refs.startPicker.innerValue = this.queryParam.start
						this.queryParam.end = Number(new Date())
						this.$refs.endPicker.innerValue = this.queryParam.end
						return
					}else{
						this.getHistoryData();
					}
				}
			},
			async getHistoryData() {
				try {
					this.chartData = {}
					this.ischange = false
					const param =this.queryParam;
					if(!param.start||!param.end){
						return;
					};
					/* const timeFormat = uni.$u.timeFormat;
					param.start= timeFormat(this.queryParam.start, 'yyyy-mm-dd hh:MM:ss');
					param.end= timeFormat(this.queryParam.end, 'yyyy-mm-dd hh:MM:ss'); */
					if (typeof this.queryParam.start === 'number') {
						const datax = new Date(this.queryParam.start)
						param.start = datax.toLocaleString('sv-SE').replace('T', ' ')
					}else{
						param.start = this.queryParam.start
					}
					if (typeof this.queryParam.end === 'number') {
						const datax = new Date(this.queryParam.end)
						param.end = datax.toLocaleString('sv-SE').replace('T', ' ')
					}else{
						param.end = this.queryParam.end
					}
					const  indexs= this.indexList;
					const data= {
					  categories: [],
					  series: []
					};
					let zeroSet = new Set()
					for (let index of indexs) {
						param.index = index;
						if (typeof this.queryParam.start === 'number') {
							const datax = new Date(this.queryParam.start)
							param.start = datax.toLocaleString('sv-SE').replace('T', ' ')
						}else{
							param.start = this.queryParam.start
						}
						if (typeof this.queryParam.end === 'number') {
							const datax = new Date(this.queryParam.end)
							param.end = datax.toLocaleString('sv-SE').replace('T', ' ')
						}else{
							param.end = this.queryParam.end
						}
						const result= await getHisAggData(param);
							if(result){
								
								const list = result
								for(let i=0;i<list.length;i++){
									let value = Math.floor(list[i].value * 100) / 100
									zeroSet.add(value);
									if(zeroSet.size==5){
										break
									}
								}
								
								const temp = this.currentDataList.find(item => item.pointCode ==index)
								let name = ''
								if(temp){
									name = temp.pointName + '(' + temp.unit + ')'
								}
								const serie ={
									name: name,
									data: []
								}
								const categories =[];						
								result.forEach(item => {
								  categories.push(item.time.substr(5));
								   serie.data.push(item.value);
								});
								data.series.push(serie);
								data.categories =categories;
							}
					}
					/* console.log(data) */
				   this.chartData =data;
				   if(zeroSet.size<5){
					   if(zeroSet.size>1){
						   let values = Array.from(zeroSet)
						   a:for (let i = 0; i < values.length - 1; i++) {
							   for (let j = i + 1; j < values.length; j++) {
								   if ((Math.abs(values[i] - values[j]) > 0.05) || (Math.abs(values[i] - values[j]) < -0.05)) {
									   this.opts.yAxis.splitNumber = 5
									   break a;
								   }
							   }
						   }
					   }else{
						   this.opts.yAxis.splitNumber = zeroSet.size
					   }
				   }else{
					   this.opts.yAxis.splitNumber = 5
				   }
				   this.ischange = true
				} catch (error) {
					// 处理请求失败的逻辑
					/* console.error(error); */
				}
			   
			    },
				handChangePoint(n) {
					this.indexList = n;
					this.getHistoryData();
				},		
				async  getMonitordata() {
					try {
						const result = await queryMonitordata({siteId:this.queryParam.siteId});
						if (result.appMonitorPointDataDtoList) {
								this.currentDataList = result.appMonitorPointDataDtoList;
								this.indexList.push(result.appMonitorPointDataDtoList[0].pointCode);
								this.getHistoryData();
						}	
					} catch (error) {
						// 处理请求失败的逻辑
						/* console.error(error); */
					}
			    },
				handDateClick(name) {
					if(this.ischange){
						this.dateDruingList.map((item, index) => {
							item.checked = index === name ? true : false
						})
						this.queryParam.start =  Number(new Date())- this.dateDruingList[name].code*60*60*1000;
						this.queryParam.end = Number(new Date());
						this.getHistoryData();
					}
				},
				getStyle(index){
					if(index==0){return}
					else{
						return{
							'margin-left':'10px'
						}
					}
				}
		},
		 onReady() {
			this.getMonitordata();
		  },
		// 必须要在onReady生命周期，因为onLoad生命周期组件可能尚未创建完毕
		onLoad(option) {
			this.queryParam.siteName = option.siteName;
			this.queryParam.siteId = option.siteId;
			this.pointStatus = option.status
			uni.setNavigationBarTitle({
			    title: this.queryParam.siteName
			});
		}
	};
</script>
<style lang="scss" scoped> 
	.title{
		font-family: 'PingFangSC-Medium';
		font-size: 16px;
		color: #212121;
		font-weight: 550;
	}
	.intitle{
		font-family: 'PingFangSC-Regular';
		font-size: 15px;
		color: #212121;
		font-weight: 400;
	}
</style>
